package com.margo.project.web.mvcconfig.interceptor;


import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.util.concurrent.RateLimiter;


//https://blog.csdn.net/valleychen1111/article/details/78038366
public class MargoRateLimitInterceptor implements HandlerInterceptor{

	private AtomicInteger totalRequest=new AtomicInteger(0);
	
	private AtomicInteger interceptedRequest=new AtomicInteger(0);
	
	private Logger logger=LoggerFactory.getLogger(this.getClass());
	
	private RateLimiter globalRateLimiter;

    public MargoRateLimitInterceptor(double rate) {
        if (rate > 0)
            globalRateLimiter = RateLimiter.create(rate);
        else
            throw new RuntimeException("rate must greater than zero");
    }

    public void setRate(int rate){
        globalRateLimiter.setRate(rate);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	if(request.getRequestURI().endsWith("helloworld")) {
    		totalRequest.getAndIncrement();
        	if (!globalRateLimiter.tryAcquire()) {
        		interceptedRequest.getAndIncrement();
            	logger.info(request.getRequestURI()+"请求超过限流器速率");
                return false;
            }
    	}else if(request.getRequestURI().endsWith("total")) {
    		logger.info("请求数"+totalRequest.get());
    		logger.info("被拦截请求数"+interceptedRequest.get());
    	}
    	return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
